<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, tabsEmits } from 'element-plus'
import {
  getData,
  searchData,
  addData,
  delData,
  changeData,
  checkOrInput,
  uploadImg,
  getDataById,
  getDataByStatus,
  getDataByCateId
} from '@/api/awaitList'
import { getCategory } from '@/api/category'
//工具类，获取数据用的
import { getTableList } from '@/utils/Data'
import useUserStore from '@/stores/modules/user'
const userStore = useUserStore()
// import useTable from '@/hooks/useTable'
defineOptions({ name: 'BannerIndex' })
//定义数据存放数组
const tableData = ref(0)
//定义状态数组
const STATUS_CONTENT = ref([
  { text: '未入库', value: 0 },
  { text: '已入库', value: 1 },
  { text: '二次复检中', value: 2 },
  { text: '入库失败', value: 3 }
])
//分页数据
const pag = ref({
  page: 1,
  pageSize: 10,
  pagetotal: 10
})
//获取数据
const getList = () => {
  getTableList(getData, pag, tableData)
}
getList()
//获取分类数组
const iniCategory = async () => {
  const { page, pageSize } = pag.value
  const res = await getCategory({ page, pageSize })
  CATEGORY.value = res.data.dataAll.map((item) => {
    return {
      text: item.category,
      value: item.id
    }
  })
  console.log(res)
}
iniCategory()
const CATEGORY = ref([])

//定义弹窗打开状态值
const isShow = ref(false)
//定义当前的操作值
const operation = ref('edit')

//唤出对应弹窗
const piKaChu = (newOperation, value) => {
  isShow.value = true
  operation.value = newOperation
  if (newOperation === 'edit') {
    editDialog(value)
  }
  if (newOperation === 'input') {
    INPUT_CONTENT.value.id = value.id
  }
}
//编辑弹窗逻辑
const editDialog = async (value) => {
  const res = await getDataById(value.id)
  id.value = value.id
  formData.value = res.data
  imgList.value.push({ name: res.data.id, url: res.data.image })
}
//清空弹窗内容
const clear = () => {
  isShow.value = false
  formData.value = {
    title: '',
    image: '',
    quantity: null,
    username: userStore.username,
    category: ''
  }
  INPUT_CONTENT.value = { id: null, quantity: null, code: 0, username: userStore.username }
  firstFilter.value = true // 重置过滤状态
  maxNumber.value = null
}

//表单数据
const formData = ref({
  title: '',
  image: '',
  quantity: null,
  username: userStore.username,
  categoryId: ''
})
//数字校验规则
const maxNumber = ref(null)
const isNumber = (rule, value, callback) => {
  if (typeof value !== 'number' || isNaN(value)) {
    callback(new Error('请输入数字'))
  } else if (value < 1 || (value > maxNumber.value && operation.value === 'input')) {
    console.log(11)
    callback(new Error(`数量范围为1-${maxNumber.value}`))
  } else {
    callback()
  }
}
//表单校验
const rule = ref({
  title: [{ required: true, message: '请输入货品名称', trigger: 'blur' }],
  quantity: [
    { required: true, message: '请输入数字', trigger: 'blur' },
    {
      validator: isNumber,
      trigger: 'blur'
    }
  ]
})

//入库操作数组
const INPUT = ref([
  { text: '二次复检', value: 0 },
  { text: '入库', value: 1 }
])
//入库数据
const INPUT_CONTENT = ref({
  id: null,
  quantity: null,
  code: 0,
  username: userStore.username
})

//uoload模块需要的数据
const imgUpSucess = ref(false)
const imgFile = ref(null)
const imgList = ref([])
//上传图片逻辑
const formBody = ref(null)
const upload = async () => {
  try {
    formBody.value.validate(async (ok) => {
      if (ok) {
        const res = await uploadImg(imgFile.value)
        if (res.message === 'success') {
          formData.value.image = res.data
          if (operation.value === 'add') {
            //添加内容图片接口a
            const res = await addData(formData.value)
            console.log(res)
            if (res.code === 20000) {
              ElMessage({
                type: 'success',
                message: '添加成功'
              })
            }
          } else {
            //修改内容接口
            updateContent()
          }
        }
        //重置表单
        imgUpSucess.value = false
        imgList.value = []
        clear()
        getList()
      }
    })
  } catch (error) {
    console.log(error)
  }
}
//创建图片ref
const uploadImgBody = ref(null)
//图片校验
const check = (file) => {
  const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase()
  const suffix = ['jpg', 'png', 'jpeg']
  if (!suffix.includes(fileSuffix)) {
    ElMessage({
      message: '文件类型为jpg png jpeg',
      type: 'error'
    })
    return false
  }
  if (file.size / 1024 > 500) {
    ElMessage({
      type: 'error',
      message: '图片大小不得超过500kb'
    })
    return false
  }
  try {
    const formData = new FormData()
    formData.append('file', file)
    imgFile.value = formData
    return true
  } catch (error) {
    console.log(error)
    return false
  }
}
// 删除添加的图片
const handleRemove = () => {
  //删除
  imgUpSucess.value = false
  imgList.value = []
  tableData.value.image = ''
}
const addPrompt = () => {
  imgUpSucess.value = true
  ElMessage({
    message: '添加成功'
  })
}

//提交
const ruleFormRef = ref(null)
const submit = () => {
  const fnObj = {
    async input(id) {
      ruleFormRef.value.validate(async (ok) => {
        if (ok) {
          const res = await checkOrInput(INPUT_CONTENT.value)
          if (res.code === 20000) {
            ElMessage({
              type: 'success',
              message: '入库成功'
            })
            clear()
            getList()
          }
        } else {
          ElMessage({
            type: 'error',
            message: '请按规则填写'
          })
          return false
        }
      })
    },
    edit() {
      if (imgUpSucess.value) {
        uploadImgBody.value.submit()
      } else {
        updateContent()
      }
    },
    add() {
      uploadImgBody.value.submit()
    }
  }
  fnObj[operation.value]()
}
const searchDetail = ref(null)
//搜索逻辑
const search = async (title) => {
  if (!title) {
    getList()
    return false
  }
  const res = await searchData(title)
  tableData.value = res.data
  searchDetail.value = null
}
//删除逻辑
const handleDelete = async (id) => {
  const res = await delData(id)
  ElMessage({
    type: 'success',
    message: '删除成功'
  })
  getList()
}

//更新逻辑
const id = ref(null)
const updateContent = async () => {
  const res = await changeData({ id: id.value, ...formData.value })
  console.log(res)
  if (res.code === 20000) {
    ElMessage({
      type: 'success',
      message: '修改成功'
    })
    imgUpSucess.value = false
    imgList.value = []
    clear()
    getList()
  }
}

//分类筛选
const firstFilter = ref(true)
const categorySearch = async (value, column) => {
  if (firstFilter.value) {
    firstFilter.value = false
    if (value !== undefined) {
      if (column.property === 'category') {
        const res = await getDataByCateId(value)
        tableData.value = res.data
      } else if (column.property === 'storageStatus') {
        console.log('执行了吗')
        const res = await getDataByStatus(value)
        tableData.value = res.data
      }
    } else {
      getList()
    }
  }
}
const handleFilterChange = (filters) => {
  firstFilter.value = true
  if (filters.category) {
    categorySearch(filters.category[0], { property: 'category' }) // 传递正确的 column 参数
  }
  if (filters.storageStatus) {
    // 处理 storage_status 的过滤
    categorySearch(filters.storageStatus[0], { property: 'storageStatus' }) // 传递正确的 column 参数
  }
}
</script>

<template>
  <div class="search">
    <el-input placeholder="搜索框" style="width: 240px" v-model="searchDetail"></el-input>
    <el-button @click="search(searchDetail)">搜索</el-button>
  </div>
  <el-button @click="piKaChu('add')">添加入库商品</el-button>
  <el-table style="width: 100%" :data="tableData" @filter-change="handleFilterChange">
    <el-table-column prop="id" label="ID" width="90" />
    <el-table-column prop="title" label="货品名" width="180" />
    <el-table-column prop="username" label="操作员名称" width="180" />
    <el-table-column prop="image" label="图片" width="180">
      <template #default="{ row }">
        <img :src="row.image" alt="" width="100px" height="100px" />
      </template>
    </el-table-column>
    <el-table-column prop="quantity" label="数量" width="100" />
    <el-table-column
      prop="category"
      label="分类"
      width="90"
      column-key="category"
      :filters="CATEGORY"
      :filter-method="categorySearch"
      :filter-multiple="false"
    />

    <el-table-column
      prop="storageStatus"
      label="入库状态"
      width="180"
      :filters="STATUS_CONTENT"
      column-key="storageStatus"
      :filter-method="categorySearch"
      :filter-multiple="false"
    >
      <template v-slot="{ row }">
        {{ STATUS_CONTENT[row.storageStatus].text }} : {{ row.operateQuantity }}个
      </template>
    </el-table-column>
    <el-table-column prop="updateTime" label="添加时间" width="180" />
    <el-table-column label="操作">
      <template #default="{ row }">
        <el-button
          size="small"
          type="success"
          @click="piKaChu('input', row), (maxNumber = row.quantity)"
          :disabled="row.quantity === 0"
        >
          入库
        </el-button>
        <el-button size="small" type="danger" @click="handleDelete(row.id)"> 删除 </el-button>
        <el-button
          size="small"
          type="primary"
          @click="piKaChu('edit', row)"
          :disabled="row.quantity === 0"
          :close="clear"
        >
          编辑
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog
    v-if="operation !== 'input'"
    v-model="isShow"
    width="600"
    :title="operation === 'add' ? '添加' : '更新'"
    :before-close="clear"
  >
    <el-form
      label-width="100px"
      class="demo-ruleForm"
      :model="formData"
      :rules="rule"
      ref="formBody"
    >
      <el-form-item label="产品名" prop="title">
        <el-input v-model="formData.title" />
      </el-form-item>
      <el-form-item label="产品图" class="w600">
        <el-upload
          ref="uploadImgBody"
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          :limit="1"
          :http-request="upload"
          :before-upload="check"
          :on-change="addPrompt"
          :file-list="imgList"
        >
          <template v-slot:default>
            <i class="el-icon-plus" />
          </template>
          <template #file="{ file }">
            <div>
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <el-icon><zoom-in /></el-icon>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleDownload(file)"
                >
                  <el-icon><Download /></el-icon>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <el-icon><Delete /></el-icon>
                </span>
              </span>
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="数量" prop="quantity">
        <el-input v-model.number="formData.quantity" />
      </el-form-item>
      <el-form-item label="操作员">
        <el-input v-model="formData.username" disabled />
      </el-form-item>
      <el-form-item label="分类">
        <el-select
          v-model="formData.categoryId"
          placeholder="Select"
          size="large"
          style="width: 240px"
        >
          <el-option
            v-for="item in CATEGORY"
            :key="item.value"
            :label="item.text"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <div class="dialog-footer">
        <el-button @click="clear">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-else v-model="isShow" :before-close="clear">
    <el-form :model="INPUT_CONTENT" :rules="rule" ref="ruleFormRef">
      <el-form-item label="入库数量" prop="quantity">
        <el-input placeholder="请输入数量" v-model.number="INPUT_CONTENT.quantity"></el-input>
      </el-form-item>
      <el-form-item label="货物状态">
        <el-select
          placeholder="请选择货物状态"
          size="large"
          style="width: 240px"
          v-model="INPUT_CONTENT.code"
        >
          <el-option
            v-for="item in INPUT"
            :key="item.value"
            :label="item.text"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <div class="dialog-footer">
        <el-button @click="clear">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </div>
    </template>
  </el-dialog>
  <el-pagination
    background
    layout="prev, pager, next"
    :total="pag.pagetotal"
    v-model:page-size="pag.pageSize"
    v-model:current-page="pag.page"
    @change="getList"
  />
</template>
<style lang="scss" scoped>
.el-form-item {
  width: 400px;
}

.w600 {
  width: 600px;
}
</style>
